import { asyncRoutes, constantRoutes } from '@/router'


/**
 * Use meta.role to determine if the current user has permission
 * 使用meta.role确定当前用户是否具有权限
 * @param roles asyncRoutes
 * @param route 后端
 */
// 匹配权限
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return  route.meta.roles.includes(roles)
  } else {
    return true
  }
}
  /**
   * 通过递归过滤异步路由表
   * @param routes asyncRoutes
   * @param roles 获取的后端列表
   */
  export function filterAsyncRoutes(routes, roles) {

   
    const res = []
  
    routes.forEach(route => {
      const tmp = { ...route }
      if (hasPermission(roles, tmp)) {
        if (tmp.children) {
            tmp.children = filterAsyncRoutes(tmp.children, roles)
        
        }
        res.push(tmp)
      }
    })
  
    return res
  }

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes) // 将过滤后的路由和constantRouterMap存起来
  }
}

// 筛选
const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      
      accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // 管理员
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
